package com.lanou3g.ptp.api.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.lanou3g.ptp.api.resolver.annotation.SsoStudent;
import com.lanou3g.ptp.entity.Student;
import com.lanou3g.ptp.student.service.StudentService;
import com.lanou3g.ptp.utils.PtpResult;
import com.lanou3g.ptp.utils.PtpResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Api(description = "学生接口")
@RestController
public class StudentController {

    @Reference
    private StudentService studentService;

    @ApiOperation("完善学生小程序信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "小程序code"),
            @ApiImplicitParam(name = "head", value = "头像地址")
    })
//    @PostMapping("/student/complete")
    public PtpResult completeStudent(String code, String head,
                                     @ApiIgnore @SsoStudent Student student) {
        student.setHead(head);
        boolean success = studentService.completeStudent(student, code);
        return success ? PtpResultUtils.ok() : PtpResultUtils.error(481, "完善信息失败");
    }

    @ApiOperation("查询某学校所有学生")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolId", value = "学校ID"),
            @ApiImplicitParam(name = "page", value = "页数"),
            @ApiImplicitParam(name = "size", value = "显示条数")
    })
    @GetMapping("/school/{schoolId}/students")
    public PtpResult list(@PathVariable Long schoolId,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size) {

        PageInfo<Student> all = studentService.findBySchoolId(schoolId, page, size);
        return PtpResultUtils.ok(all);
    }


    @ApiOperation("通过id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "学生id")
    })
    @DeleteMapping("/student/{id}")
    public PtpResult delete(@PathVariable Long id) {
        int i = studentService.deleteById(id);
        if (i == 0) {
            return PtpResultUtils.error(404, "没有该数据");
        } else {
            return PtpResultUtils.ok();
        }
    }

    @ApiOperation("通过id 多个删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "多个学生id")
    })
    @DeleteMapping("/students/{ids}")
    public PtpResult deletes(@PathVariable List<Long> ids) {
        int i = studentService.deleteByIds(ids);
        if (i == 0) {
            return PtpResultUtils.error(404, "没有该数据");
        } else {
            return PtpResultUtils.ok();
        }
    }


    @ApiOperation("修改学生信息")
    @PutMapping("/student/{id}")
    public PtpResult upStudent(@PathVariable Long id,
                               @RequestBody Student student) {
        student.setId(id);
        student.getUser().setId(id);
        int i = 0;
        try {
            i = studentService.upStuById(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i == 0) {
            return PtpResultUtils.error(404, "没有该数据");
        } else {
            return PtpResultUtils.ok();
        }
    }

    @ApiOperation("添加信息")
    @PostMapping("/student")
    public PtpResult addStudent(@RequestBody Student student) {
        int i = 0;
        try {
            i = studentService.insetStudent(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (i == 0) {
            return PtpResultUtils.error(404, "没有该数据");
        } else {
            return PtpResultUtils.ok();
        }
    }

    @ApiOperation("导入学生Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentUploadFile", value = "学生信息Excel表.xlsx")
    })
    @PostMapping("/student/import")
    public PtpResult importStudent(@RequestBody byte [] bytes) throws IOException {
        int count = studentService.excelToStudentInfo(bytes);
        return count>0 ? PtpResultUtils.ok(count):PtpResultUtils.error(500);
    }


    //    TODO 测试导入学生
    @ApiOperation("测试导入学生文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "testFile", value = "测试文件接收")
    })
    @PostMapping("/student/test")
    public PtpResult test(MultipartFile file) {
        InputStream inputStream;
        int count = 0;
        try {
            inputStream = file.getInputStream();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            count = studentService.excelToStudentInfo(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return count > 0 ? PtpResultUtils.ok(count) : PtpResultUtils.error(500);
    }



    @ApiOperation("导出学生Excel模板")
    @GetMapping("/student/model")
    public void modelStudent(HttpServletResponse response) {
        response.reset();
        response.setContentType("application/msexcel;charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("学生信息样表.xlsx", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] bytes = studentService.excelStudentModel();
        try {
            IOUtils.write(bytes, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
